<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>泉城投票</title>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="./css/frozen.css">
    <link rel="stylesheet" href="./css/vote.css">
    <script src="js/jquery.min.js"></script>
    
</head>
<body>
<div id="mainWrap">
</div>
<script src="js/artTemplate/artTemplate.js"></script>
<script src='js/vote-tpl.js'></script>
<script src="js/layer/layer.js"></script>
<script>
    var url = '/';
    window.parameter = GetRequest(window.location.href);
    //window.parameter.vote_id = 'ecefbde8-ac8f-41bf-b017-bb9b0e4e68d4';
    window.commonData = {};
    /*
     * 获取?后面的参数并返回 json 对象
     */
    function GetRequest(url) {
        if(!url || url.indexOf('?') == -1){
            return {};
        }
        var url = url.split('?')[1].split('#')[0]; //获取url中"?"符后"#"前的字串
        var theRequest = new Object();
        var str = decodeURI(url);
        var strs;
        if (str.indexOf("&") != -1) {
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        } else {
            theRequest[str.split("=")[0]] = unescape(str.split("=")[1]);
        }
        theRequest['vote_id'] = theRequest['act_id'];
        return theRequest;
    }


    function bindEvent() {
        //IOS中激活a标签active事件
        var a = document.getElementsByTagName('a');
        for (var i = 0; i < a.length; i++) {
            a[i].addEventListener('touchstart', function() {}, false);
        }
        document.body.addEventListener('touchstart', function() {});

        $('#mainWrap').on('click', '.voteTab li', function() {

            var index = $(this).index();
            $(this).addClass('cur').siblings('li').removeClass('cur');
            $('.tabList').hide().eq(index).show();
            if (index == 2) {
                layer.open({type: 2,shadeClose:false});
                rankDateCallBack();
            }
        })
        $('body').on('click', '.closeItem', function() {
            layer.closeAll();
        })

        //列表投票按钮触发事件
        $('#mainWrap').on('click', '.voteBtnItem', function() {
            //  	if((!window.parameter.userid&&!window.parameter.uid) || (window.parameter.userid==null&&window.parameter.uid == null) ){
            //  		layer.open({
            //  			shadeClose:false,
            // 	className: 'messageStyle'
            // 	,content: '请下载APP参与投票'
            // });
            // setTimeout(function(){
            // 	window.location.href = window.location.origin+window.location.pathname+window.location.search+'&noLogin=true';
            // },1000)
            // return;
            //  	}
            layer.open({type: 2,shadeClose:false});
            var type = $(this).attr('voteType');
            var vId = $(this).attr('voteId');
            itemCallBack(vId,type);
        })

        //搜索按钮
        $('#mainWrap').on('click', '#searchBtn', function(){
            layer.open({type: 2,shadeClose:false});
            searchCallBack($(this).prev('input').val());
        })

        //投票按钮
        $('body').on('click', '.voteBtn', function() {
            if(!window.parameter.uid&&!window.parameter.mfSign){
                layer.open({
                    shadeClose:false,
                    className: 'messageStyle'
                    ,content: '请下载APP参与投票'
                });
                return;
            }

            if(!window.parameter.uid && window.parameter.mfSign){
                var paramJson =GetRequest(window.location.href);
                var param='';
                //有noLogin参数
                if(window.location.search.indexOf('noLogin') != -1){
                    $.each(paramJson,function(val,i){
                        if(val != 'noLogin'){
                            param += val +'='+ paramJson[val]+'&'
                        }
                    })
                    param = param.slice(0,-1);
                    window.location.href = window.location.origin+window.location.pathname+'?'+param+'&noLogin=true';
                }else{//没noLogin参数
                    window.location.href = window.location.origin+window.location.pathname+window.location.search+'&noLogin=true';
                }
                return;
            }

            var item_id = $(this).attr('voteId');
            var uid = window.parameter.uid;
            voteCallBack(item_id,uid);
            return false;
        })
    }




    /**
     * 验证sign
     */
    function signCallBack() {
        // var data = delete window.parameter.vote_id;
        //     data = delete data.noLogin;
        layer.open({type: 2,shadeClose:false});
        $.ajax({
            url: url + 'api/app/sign/mf.php',
            data:window.parameter,
            type: 'get',
            success: function(ajaxData) {
                if (ajaxData.code == '200') {
                    listDateCallBack();
                } else {
                    layer.open({
                        className: 'messageStyle'
                        ,content: ajaxData.message
                    });
                }
            }
        })
    }

    //没有uid 和 userid 不验签
    if(!window.parameter.userid&&!window.parameter.uid){
        listDateCallBack();
    }else{
        signCallBack();
    }

    /**
     * 获取投票列表数据
     * @return  {[type]}  [description]
     */
    function listDateCallBack() {
        $.ajax({
            url: url + 'lua/api/vote/details',
            data: {
                vote_id: window.parameter.vote_id
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {

                    //转换items的{} 为 [] 格式 方便模板遍历
                    var dealItems = [];
                    $.each(ajaxData.data.details.categories,function(i,val){
                        if(ajaxData.data.details.items[val.id]){
                            dealItems.push({
                                group_name :  val.title,
                                data : ajaxData.data.details.items[val.id]
                            })
                        }

                    })
                    console.log(dealItems);
                    //供详情等页面用
                    commonData = ajaxData.data.details;
                    ajaxData.data.details.dealItems = dealItems;
                    data = ajaxData.data;
                    details = data.details;
                    var tplHTML = voteTpl.mainHtml({
                        data: data
                    });
                    $('#mainWrap').html(tplHTML);
                    $('#rules').html(details.rules);
                    bindEvent();
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message,
                    });
                }
            }
        })
    }
    //listDateCallBack();


    /**
     * 获取排名列表数据
     * @return  {[type]}  [description]
     */
    function rankDateCallBack() {
        $.ajax({
            url: url + 'lua/api/vote/rank',
            data: {
                vote_id: window.parameter.vote_id
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    var tplHTML = voteTpl.rank({
                        data: ajaxData
                    });
                    $('#rankBox').html(tplHTML);
                } else {
                    layer.open({
                        className: 'messageStyle'
                        ,content: ajaxData.message
                    });
                }
            }
        })
    }

    /**
     * 投票详情
     * item_id : 候选项的id
     * type : 详情类型 1 图片 2 音频 3 视频 4 外链
     */
    function itemCallBack(item_id,type) {
        $.ajax({
            url: url + 'lua/api/vote/item',
            data: {
                'vote_id': window.parameter.vote_id,
                'id': item_id
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    // var tplHTML = voteTpl.rank({data:ajaxData});
                    // $('#rankBox').html(tplHTML);
                    layer.open({
                        type: 1,
						  zIndex:999,
                        content: '<div style="background-color:#fff;height:' + $(window).height() + 'px"><i class="closeItem" ></i>' + voteTpl['items' + type]({
                            data: {data:ajaxData.data,commonData:window.commonData}
                        }) + '</div>',
                        style: 'position:absolute; bottom:0; left:0; top:0; right:0; padding:0; border:none;    overflow: auto;'
						success: function(layero){
						  // hack处理layer层中video播放器全屏样式错乱问题
						  setTimeout(function() {
							$(layero).removeClass('layer-anim');
						  }, 0);
						 }
					});
                } else {
                    layer.open({
                        className: 'messageStyle'
                        ,content: ajaxData.message
                    });
                }
            }
        })
    }

    /**
     * 投票详情
     * `q`: 关键字 （只能完全匹配）
     */
    function searchCallBack(q) {
        $.ajax({
            url: url + 'lua/api/vote/search',
            data: {
                'vote_id': window.parameter.vote_id,
                'q': q
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == 200) {
                    var tplHTML = voteTpl.search({
                        data: ajaxData.data
                    });
                    $('#searchBox').html(tplHTML);
                } else {
                    $('#searchBox').html('<p class="noResults">'+ajaxData.message+'</p>');
                    //             layer.open({
                    // 	className: 'messageStyle'
                    // 	,content: ajaxData.message
                    // });
                }
            }
        })
    }
    /**
     * 投票
     *  `item_id`: 候选项的id
     *  `uid`: 用户id
     */
    function voteCallBack(item_id, uid) {
        var index = layer.open({type: 2,shadeClose:false});
        var postData = {
            'vote_id': window.parameter.act_id,
            'item_id': item_id,
            'uid': window.parameter.uid
        };
        postData = $.extend({},postData,window.parameter);
        $.ajax({
            url: url + 'lua/api/vote/vote',
            data: postData,
            type: 'get',
            success: function(ajaxData) {
                layer.close(index);
                if(ajaxData.code == 200) {
                    $('#vote1_'+item_id).html(parseInt($('#vote1_'+item_id).html())+1);
                    $('#vote_'+item_id).html(parseInt($('#vote_'+item_id).html())+1+"票");
                    layer.open({
                        time:1,
                        className: 'messageStyle'
                        ,content: ajaxData.message
                    });
                }else {
                    layer.open({
                        className: 'messageStyle'
                        ,content: ajaxData.message
                    });
                }
            }
        })
    }
</script>
</body>

</html>
